#include <mutex>
#include <condition_variable>
#include <atomic>
#include <thread>
#include <vector>
#include <functional>
#include <future>

#include <iostream>

class ThreadPool
{
public:
    using Functor = std::function<void()>;
    ThreadPool(int thread_count = 1)
        : _stop(false)
    {
        for (int i = 0; i < thread_count; i++)
        {
            _threads.emplace_back(&ThreadPool::entry, this);
        }
    }
    ~ThreadPool()
    {
        Stop();
    }
    void Stop()
    {
        if (_stop) return;
        _stop = true;
        std::unique_lock<std::mutex> lock(_mtx);
        _cond.notify_all();
        for (auto &thread : _threads)
            thread.join();
    }
    template <typename Fn, typename... Args>
    auto push(Fn&& func, Args&& ...args) -> std::future<decltype(func(args...))>
    {
        using return_type = decltype(func(args...));
        auto myfunc = std::bind(std::forward<Fn>(func), std::forward<Args>(args)...);
        auto ptask = std::make_shared<std::packaged_task<return_type()>>(myfunc);
        std::future<return_type> fu = ptask->get_future();
        {
            std::unique_lock<std::mutex> lock(_mtx);
            if (!_stop)
            {
                _tasks.emplace_back([ptask](){
                    (*ptask)();
                });
            }
            _cond.notify_one();
        }
        return fu;
    }
private:
    void entry()
    {
        while (!_stop)
        {
            std::vector<Functor> tasks;
            {
                std::unique_lock<std::mutex> lock(_mtx);
                _cond.wait(lock, [this]()
                           { return _stop || !_threads.empty(); });
                tasks.swap(_tasks);
            }
            for (const auto &task : tasks)
            {
                task();
            }
        }
    }

private:
    std::mutex _mtx;
    std::condition_variable _cond;
    std::atomic<bool> _stop;
    std::vector<std::thread> _threads;
    std::vector<Functor> _tasks;
};

int Add(int num1, int num2)
{
    return num1 + num2;
}

int main()
{
    ThreadPool pool;
    for (int i = 0; i < 10; i++)
    {
        std::future<int> fu = pool.push(Add, 11, i);
        std::cout << fu.get() << std::endl;
    }

    return 0;
}